package com.iseastar.guojiang.station;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.AppCaptureActivity;
import com.iseastar.guojiang.app.Intents;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.CabinetBean;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.StationParcelBean;
import com.iseastar.guojiang.model.StationParcelResult;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.shouhuobao.station.R;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

import droid.frame.ui.dialog.AppDialog;
import droid.frame.umeng.UMeng;
import droid.frame.view.SwipeListViewOnScrollListener;

/**
 * 裹将到驿站、核对包裹 列表界面
 *
 * @author coffee<br>
 *         2016-11-30下午2:32:34
 */
public class StationParcelListActivity extends BaseActivity2 implements OnClickListener {

    private ListView mListView;
    //
    private StationParcelListAdapter mAdapter;
    // 从网上查询的备份数据
    private ArrayList<StationParcelBean> mItemsBak;
    // 输入框
    private EditText mEditInput;
    // 选中的包裹数量
    private TextView mParcelCount;
    // 全选
    private CheckBox mCheckButton;
    //
    private Button mSubmit;
    /**
     * 提交请求的时候正在操作的id
     */
    private HashSet<Integer> ids;
    // 当前正在操作的item
    private StationParcelBean clickItem;
    private String parcelId;//要绑定袋子的包裹ID

    @Override
    @SuppressLint("ResourceAsColor")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showLoadingDialog("查询中");
        // 驿站id
        CabinetBean.StationCabubetBean clickItem = AppCache.getCabinetOrStation();
        AppHttp.getInstance().stationGetAlls(clickItem.getId());
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.station_check);
        super.findViewById();
        getAppTitle().setCommonTitle("核对包裹信息");
        mEditInput = (EditText) findViewById(R.id.station_check_input);
        mListView = (ListView) findViewById(R.id.listview);
        mAdapter = new StationParcelListAdapter(null, getContext(), mListView);
        mListView.setAdapter(mAdapter);
        //
        mCheckButton = (CheckBox) findViewById(R.id.station_check);
        mCheckButton.setOnClickListener(this);
        mParcelCount = (TextView) findViewById(R.id.station_check_count);
        mSubmit = (Button) findViewById(R.id.station_submit);
        //
        mSubmit.setOnClickListener(this);
        findViewById(R.id.station_scan).setOnClickListener(this);
        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mAdapter.isEmpty()) {
                    return;
                }
                StationParcelBean item = (StationParcelBean) parent.getItemAtPosition(position);
                toDetails(item);
            }
        });
        // update
        updateCount();

        mEditInput.addTextChangedListener(new TextWatcherExt() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 4) {
                    UMeng.click(getContext(), "station_query_bylast4_click");
                    ArrayList<StationParcelBean> filterItems = new ArrayList<StationParcelBean>();
                    for (StationParcelBean item : mAdapter.getItems()) {
                        if (TextUtils.isEmpty(item.getBagCode()) || "null".equals(item.getBagCode())) {
                            continue;
                        }
                        if (item.getBagCode().trim().endsWith(s.toString())) {
                            filterItems.add(item);
                        } else {
                            // 如果不包含, 并且在选中列表中 ，则移除
                            if (mAdapter.getCheckIds().size() != 0) {
                                mAdapter.getCheckIds().remove(item.getParcelId());
                                updateCount();
                            }
                        }
                    }
                    mAdapter.setItems(filterItems, true);
                } else {
                    mAdapter.setItems(mItemsBak, true);
                }
            }
        });

        mListView.setFooterDividersEnabled(true);

        // 刷新包裹列表
        mSwipeLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                CabinetBean.StationCabubetBean clickItem = AppCache.getCabinetOrStation();
                AppHttp.getInstance().stationGetAlls(clickItem.getId());
            }
        });
        mListView.setOnScrollListener(new SwipeListViewOnScrollListener(mSwipeLayout));
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 通过驿站编码查询包裹
            case MsgID.station_getList_by_id:
                onRefreshComplete();
                cancelLoadingDialog();
                // final ReqResult<StationParcelBean> result = JSON.parseList(msg.obj, StationParcelBean.class);
                final ReqResult<StationParcelResult> result = JSON.parser(msg.obj, StationParcelResult.class);
                if (checkLoginStatus(result)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TextView count = (TextView) findViewById(R.id.station_parcel_count);
                            // count.setVisibility(View.VISIBLE);
                            // ArrayList<StationParcelBean> items = result.getResultList();
                            StationParcelResult result2 = result.getResult();
                            if (result2 == null) {
                                return;
                            }
                            ArrayList<StationParcelBean> unPayed = null;
                            if (result2.getUnPayed() != null) {
                                unPayed = result2.getUnPayed();
                            } else {
                                unPayed = new ArrayList<>();
                            }
                            ArrayList<StationParcelBean> payed = null;
                            if (null != result2.getPayed()) {
                                payed = result2.getPayed();
                            } else {
                                payed = new ArrayList<>();
                            }
                            mAdapter.getCheckIds().clear();
                            // 没有未支付，隐藏等待支付
                            mAdapter.setUnPayCount(unPayed.size());
                            mAdapter.setPayedCount(payed.size());
                            unPayed.addAll(payed);
                            mAdapter.setItems(unPayed, true);
                            // 备份
                            mItemsBak = new ArrayList<StationParcelBean>();
                            mItemsBak.addAll(unPayed);
                            if (mAdapter.getUnPayCount() > 0) {
                                findViewById(R.id.parcel_wait_pay_item).setVisibility(View.VISIBLE);
                                TextView parcelCount = (TextView) findViewById(R.id.parcel_cellect_count);
                                TextView payCount = (TextView) findViewById(R.id.parcel_need_pay_cost);
                                parcelCount.setText("共" + mAdapter.getItemsSize() + "个包裹待揽收(" + mAdapter.getUnPayCount() + "个未支付)");
                                payCount.setText("对方需支付" + result2.getToatlPrice() + "元");
                            } else {
                                findViewById(R.id.parcel_wait_pay_item).setVisibility(View.GONE);
                            }
                            // count.setText("共" + items.size() + "个包裹待揽收");
                        }
                    });
                }else {
                    showToast(result.getMessage());
                }
                return true;
            // 核对包裹、揽收
            case MsgID.station_parcel_check:
                cancelLoadingDialog();
                final ReqResult<?> result2 = JSON.parser(msg.obj);
                if (checkLoginStatus(result2)) {
                    showToast(result2.getMessage());
                    for (Iterator<StationParcelBean> it = mAdapter.getItems().iterator(); it.hasNext(); ) {
                        StationParcelBean item = it.next();
                        if (ids != null && ids.contains(item.getParcelId())) {
                            it.remove();
                        }
                    }
                    mItemsBak.clear();
                    mItemsBak.addAll(mAdapter.getItems());
                    ids.clear();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToast(result2.getMessage());
                            mAdapter.notifyDataSetChanged();
                            if (mAdapter.isEmpty()) {
                                finish();
                            }
                            updateCount();
                        }
                    });
                    CabinetBean.StationCabubetBean clickItem = AppCache.getCabinetOrStation();
                    AppHttp.getInstance().stationGetAlls(clickItem.getId());
                    // Intent intent = new Intent(this, StationCellectedSuccessActivity.class);
                    // startActivity(intent);
                } else {
                    showToast(result2.getMessage());
                }
                return true;
            //进行袋子和包裹绑定
            case MsgID.bagcode_bindparcel:
                cancelLoadingDialog();
                ReqResult<?> result1 = JSON.parser(msg.obj);
                if (checkLoginStatus(result1)) {
                    showToast("绑定成功");
                    showLoadingDialog(null);
                    CabinetBean.StationCabubetBean clickItem = AppCache.getCabinetOrStation();
                    AppHttp.getInstance().stationGetAlls(clickItem.getId());
                } else {
                    showToast(result1.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    public void updateCount() {
        int count = mAdapter.getCheckIds().size();
        if (count > 0 && mAdapter.getItems().size() == count) {
            mCheckButton.setChecked(true);
        } else {
            mCheckButton.setChecked(false);
        }
        if (count == 0) {
            setButtonEnableStyle(mSubmit, false);
        } else {
            setButtonEnableStyle(mSubmit, true);
        }
        String format = "已选择" + count + "个包裹";
        SpannableString ss = new SpannableString(format);
        ss.setSpan(new ForegroundColorSpan(Color.parseColor("#F7622E")), 3, 4, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        mParcelCount.setText(ss);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 全选|取消
            case R.id.station_check:
                CheckBox check = (CheckBox) v;
                // 当前选中
                mAdapter.checkAlls(check.isChecked());
                updateCount();
                break;
            // 检查包裹
            case R.id.station_scan:
                UMeng.click(getContext(), "station_query_byscan_click");
                Intent intent = new Intent();
                intent.setClass(getContext(), AppCaptureActivity.class);
                intent.setAction(Intents.guojiang_check_parcel);
                startActivityForResult(intent, 101);
                break;
            // 揽收包裹
            case R.id.station_submit:
                int count = mAdapter.getCheckIds().size();
                if (count == 0) {
                    showToast("选择揽收的包裹");
                    return;
                }
                boolean fag = false;
                HashSet<Integer> hashSet = mAdapter.getCheckIds();
                for (Integer integer : hashSet) {
                    for (StationParcelBean bean : mAdapter.getItems()) {
                        if (integer == bean.getParcelId() && (TextUtils.isEmpty(bean.getBagCode()) || "null".equals(bean.getBagCode()))) {
                            fag = true;
                            break;
                        }
                    }
                }
                if (fag) {
                    showToast("还有包裹未绑定投递编号,请先进行绑定,再进行揽收");
                    return;
                }
                final AppDialog dialog = new AppDialog(getContext());
                dialog.setContent("你将揽收" + count + "个包裹");
                dialog.setCancelClickListener("取消", null);
                dialog.setConfirmClickListener("确定", new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showLoadingDialog(null);
                        ids = mAdapter.getCheckIds();
                        CabinetBean.StationCabubetBean clickCabinetOrStation = AppCache.getCabinetOrStation();
                        AppHttp.getInstance().stationParclCheck(clickCabinetOrStation.getSenderPhone(), //
                                mAdapter.getCheckIds().toString());
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
        }
    }

    public void setBindParcelId(String parcelId) {
        this.parcelId = parcelId;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 101 && resultCode == RESULT_OK) {
            String result = data.getStringExtra("result");
            int index = result.lastIndexOf("=");
            String code2;
            if (index > -1) {
                code2 = result.substring(index + 1, result.length());
            } else {
                code2 = result;
            }
            StationParcelBean item = checkParcelByCode(code2);
            if (item != null) {
                toDetails(item);
            } else {
                showToast("代收列表中没有此包裹");
            }
        }
        // 拒收 或者 异常申报
        else if (requestCode == 102 && resultCode == RESULT_OK) {
            CabinetBean.StationCabubetBean clickItem = AppCache.getCabinetOrStation();
            AppHttp.getInstance().stationGetAlls(clickItem.getId());
            //            mAdapter.getItems().remove(clickItem);
            //            mItemsBak.remove(clickItem);
            //            mAdapter.getCheckIds().remove(clickItem.getParcelId());
            //            updateCount();
            //            if (mAdapter.getUnPayCount() > 0) {
            //                findViewById(R.id.parcel_wait_pay_item).setVisibility(View.VISIBLE);
            //                TextView parcelCount = (TextView) findViewById(R.id.parcel_cellect_count);
            //                TextView payCount = (TextView) findViewById(R.id.parcel_need_pay_cost);
            //                parcelCount.setText("共" + mAdapter.getItemsSize() + "个包裹待揽收(" + mAdapter.getUnPayCount() + "个未支付)");
            //                payCount.setText("对方需支付" + (mAdapter.getUnPayCount()* )+ "元");
            //            } else {
            //                findViewById(R.id.parcel_wait_pay_item).setVisibility(View.GONE);
            //            }
            mAdapter.notifyDataSetChanged();
        }
        //扫描袋子后返回,检验袋子是否可用
        else if (requestCode == 103 && resultCode == RESULT_OK) {
            String bagcode = data.getStringExtra("result");
            int index = bagcode.lastIndexOf("=");
            String code2;
            if (index > -1) {
                code2 = bagcode.substring(index + 1, bagcode.length());
            } else {
                code2 = bagcode;
            }
            showLoadingDialog(null);
            AppHttp.getInstance().bagCodeBindParcel(code2, parcelId);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 跳转到详情页面
     *
     * @param item
     */
    private void toDetails(StationParcelBean item) {
        clickItem = item;
        Intent intent = new Intent();
        intent.setClass(getContext(), StationParcelDetailsActivity.class);
        intent.putExtra("item", item);
        startActivityForResult(intent, 102);
    }

    /**
     * 按照条形码 扫描包裹
     *
     * @param code
     * @return
     */
    private StationParcelBean checkParcelByCode(String code) {
        StationParcelBean result = null;
        for (StationParcelBean item : mAdapter.getItems()) {
            if (isEquals(item.getBagCode(), code)) {
                return item;
            }
        }
        return result;
    }

}
